<template>
  <el-card class="mb-20">
    <template #header>
      <div class="card-header">
        <div class="header-title">
          <span>任务目标配置</span>
          <el-tooltip content="配置需要同步的目标表字段信息" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
        <el-button type="primary" size="small" @click="handleAddColumn" :disabled="!hasColumns">
          <el-icon><Plus /></el-icon>添加列
        </el-button>
      </div>
    </template>
    
    <div v-if="!form.details || form.details.length === 0" class="empty-tip">
      <el-empty description="暂无目标列配置">
        <template #image>
          <el-icon class="empty-icon"><DataLine /></el-icon>
        </template>
        <template #description>
          <div>
            <p>暂无目标列配置</p>
            <p class="small-tip">请先选择数据源和表名，然后点击"添加列"按钮添加要同步的列</p>
          </div>
        </template>
        <el-button type="primary" @click="handleAddColumn" :disabled="!hasColumns">添加列</el-button>
      </el-empty>
    </div>
    
    <div v-else>
      <el-alert
        title="目标列配置说明"
        type="info"
        :closable="false"
        show-icon
        class="alert-tip"
      >
        配置需要同步的目标表列信息，可以从可用列列表中选择。
      </el-alert>
      
      <el-table 
        ref="tableRef"
        :data="form.details" 
        style="width: 100%" 
        border
        :height="tableHeight"
        highlight-current-row
        class="target-table"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="列名" prop="column_name">
          <template #default="{ row, $index }">
            <el-select 
              v-model="row.column_name" 
              placeholder="请选择列名"
              style="width: 100%"
              filterable
              @change="(val) => handleColumnChange(val, $index)"
            >
              <el-option
                v-for="column in columnOptions"
                :key="column"
                :label="column"
                :value="column"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="目标表的列名" placement="top">
              <span>列名<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="comment">
          <template #default="{ row }">
            <el-input v-model="row.comment" placeholder="请输入备注" />
          </template>
          <template #header>
            <el-tooltip content="该列的备注说明" placement="top">
              <span>备注<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              circle
              @click="handleDeleteColumn($index)"
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-button type="primary" size="small" plain @click="handleAddColumn" :disabled="!hasColumns">
          <el-icon><Plus /></el-icon>继续添加
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { defineProps, ref, onMounted, nextTick, computed, watch } from 'vue';
import { Delete, Plus, DataLine, QuestionFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 定义props
const props = defineProps({
  form: {
    type: Object,
    required: true
  },
  columnOptions: {
    type: Array,
    default: () => []
  }
});

// 表格引用
const tableRef = ref(null);
const tableHeight = ref("auto");

// 判断是否有可选列
const hasColumns = computed(() => props.columnOptions.length > 0);

// 添加一个列配置
const handleAddColumn = () => {
  if (!props.form.details) {
    props.form.details = [];
  }
  
  props.form.details.push({
    column_name: '',
    comment: ''
  });
  
  // 添加数据后刷新表格以确保表头显示
  nextTick(() => {
    refreshTableLayout();
  });
};

// 删除一个列配置
const handleDeleteColumn = (index: number) => {
  const columnName = props.form.details[index].column_name;
  props.form.details.splice(index, 1);
  
  // 如果删除的列被用于目源关系配置，也需要移除相应的映射
  if (columnName && props.form.ts_mapping) {
    props.form.ts_mapping = props.form.ts_mapping.filter((mapping: any) => 
      mapping.target_column_name !== columnName
    );
  }
  
  // 删除数据后刷新表格
  nextTick(() => {
    refreshTableLayout();
  });
};

// 列名变更事件
const handleColumnChange = (value: string, index: number) => {
  // 检查是否有重复的列名
  const isDuplicate = props.form.details.some((detail: any, i: number) => 
    detail.column_name === value && i !== index
  );
  
  if (isDuplicate) {
    ElMessage.warning(`列名 ${value} 已经被选择，请选择其他列名`);
    props.form.details[index].column_name = '';
    return;
  }
  
  // 如果这个列名之前被用于映射关系，需要更新相关的映射
  const oldColumnName = props.form.details[index].column_name;
  if (oldColumnName && props.form.ts_mapping) {
    props.form.ts_mapping.forEach((mapping: any) => {
      if (mapping.target_column_name === oldColumnName) {
        mapping.target_column_name = value;
      }
      if (mapping.target_query_column === oldColumnName) {
        mapping.target_query_column = value;
      }
    });
  }
};

// 表格布局刷新函数
const refreshTableLayout = () => {
  if (tableRef.value) {
    // @ts-ignore
    tableRef.value.doLayout();
    
    // 触发窗口 resize 事件，让表格重新计算布局
    window.dispatchEvent(new Event('resize'));
  }
};

// 监听表格数据和列选项变化
watch(
  () => [props.form.details?.length, props.columnOptions.length],
  () => {
    nextTick(() => {
      refreshTableLayout();
    });
  }
);

// 组件挂载后确保表格布局正确
onMounted(() => {
  // 确保表格在DOM完全渲染后重新布局
  setTimeout(() => {
    refreshTableLayout();
  }, 300);
});
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
}

.help-icon {
  margin-left: 4px;
  font-size: 14px;
  color: #909399;
}

.empty-tip {
  padding: 20px 0;
}

.empty-icon {
  font-size: 60px;
  color: #909399;
}

.small-tip {
  font-size: 12px;
  color: #909399;
}

.alert-tip {
  margin-bottom: 15px;
  font-size: 13px;
}

.table-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.target-table :deep(th) {
  display: table-cell !important;
}

.target-table :deep(thead) {
  display: table-header-group !important;
}

.target-table :deep(.el-table__header) {
  display: table !important;
}
</style>